import axios from "axios"
import { message } from "antd"
const request = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
  timeout: 5000
})

request.interceptors.request.use(
  (config) => {
    //config 是请求的配置对象;
    //config.url 是用来获取请求的地址的;
    // 在发送请求之前做些什么
    let whitepath = ['/login']
    if(whitepath.includes(config?.url)){
      return config
    }
    //获取token
    let token = localStorage.getItem('token');
    if(token){
        config.headers['Authorization'] = token
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

request.interceptors.response.use(
  (response) => {
    return response
  },
  (error) => {
    //统一处理错误的状态码
    if(error.response.status === 400){
      // 404 未找到，跳转到404页
      message.error('参数错误')
    }
    if(error.response.status === 401){
      // 401 未授权，跳转到登录页
      window.location.href = '/login'
    }else if(error.response.status === 500){
        message.error(error.response.data.message)
    }
    return Promise.reject(error)
  }
)


export default request
